package com.boot.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Slf4j
@Controller
public class LoginController {

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(String userName, String password, Model model){

        UsernamePasswordToken token = new UsernamePasswordToken(userName,password);

        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            log.error("未发现用户名:{}",e.getMessage());
            model.addAttribute("error","用户名/密码错误");
            return "login";
        } catch (IncorrectCredentialsException e) {
            log.error("错误的密码:{}",e.getMessage());
            model.addAttribute("error","用户名/密码错误");
            return "login";
        } catch (AuthenticationException e) {
            log.error("其他错误:{}",e.getMessage());
            //其他错误，比如锁定，如果想单独处理请单独catch处理
            model.addAttribute("error","其他错误：" + e.getMessage());
            return "login";
        }

        return "redirect:/index";
    }

}
